<?php
require_once get_theme_file_path() . '/inc/codestar-framework/codestar-framework.php';
// require_once get_theme_file_path() . '/inc/codestar-framework/samples/admin-options.php';
require_once get_theme_file_path() . '/inc/admin-options.php';
require_once get_theme_file_path() . '/inc/fun-menus.php';
require_once get_theme_file_path() . '/inc/fun-widgets.php';
require_once get_theme_file_path() . '/inc/fun-ajax.php';
require_once get_theme_file_path() . '/inc/jiangqie-user-avatar.php';

/**
 * 开启链接管理
 */
add_filter('pre_option_link_manager_enabled', '__return_true');

/**
 * 移除图片的宽高属性
 */
add_filter('post_thumbnail_html', 'remove_width_attribute', 10);
add_filter('image_send_to_editor', 'remove_width_attribute', 10);
function remove_width_attribute($html)
{
    $html = preg_replace('/(width|height)="\d*"\s/', "", $html);
    return $html;
}

/**
 * 开启特色图功能
 */
if (function_exists('add_theme_support')) {
    add_theme_support('post-thumbnails');
}

// 在init action处注册脚本，可以与其它逻辑代码放在一起
function jiangqie_theme_init()
{
    $url = get_template_directory_uri();

    // 注册样式表
    // wp_register_style('jq-style', get_stylesheet_uri(), [], '0.3', true);

    // 注册脚本
    // wp_register_script('jquery', 'https://cdn.bootcdn.net/ajax/libs/jquery/1.9.1/jquery.min.js');
    wp_register_script('lib-script', $url . '/js/lib/lb.js', [], '0.3');
    wp_register_script('lib-layer', $url . '/js/layer/layer.js', ['jquery'], '1.0', false);
    wp_register_script('jq-footer-script', $url . '/js/jiangqie.footer.js', ['jquery'], '0.3', true);
    wp_register_script('jq-index-script', $url . '/js/jiangqie.index.js', ['jquery', 'lib-script'], '0.4', true);
    wp_register_script('jq-archive-script', $url . '/js/jiangqie.archive.js', ['jquery'], '0.4', true);
    wp_register_script('jq-single-script', $url . '/js/jiangqie.single.js', ['lib-layer'], '0.3', true);

    // 其它需要在init action处运行的脚本
}
add_action('init', 'jiangqie_theme_init');


function jiangqie_scripts()
{
    //全局加载主样式表
    // wp_enqueue_style('jq-style');

    //全局加载js脚本
    wp_enqueue_script('jquery');
    wp_enqueue_script('jq-footer-script');

    if (is_home()) {
        wp_enqueue_script('lib-script');
        wp_enqueue_script('jq-index-script');
    }

    if (is_archive()) {
        wp_enqueue_script('jq-archive-script');
    }

    if (is_single()) {
        wp_enqueue_script('lib-layer');
        wp_enqueue_script('jq-single-script');

    }
}
add_action('wp_enqueue_scripts', 'jiangqie_scripts');

/**
 *  清除谷歌字体 
 */
function jiangqie_remove_open_sans_from_wp_core()
{
    wp_deregister_style('open-sans');
    wp_register_style('open-sans', false);
    wp_enqueue_style('open-sans', '');
}
add_action('init', 'jiangqie_remove_open_sans_from_wp_core');

/**
 * 清除wp_head无用内容 
 */
function remove_dns_prefetch($hints, $relation_type)
{
    if ('dns-prefetch' === $relation_type) {
        return array_diff(wp_dependencies_unique_hosts(), $hints);
    }
    return $hints;
}
function jiangqie_remove_laji()
{
    remove_action('wp_head', 'wp_generator'); //移除WordPress版本
    remove_action('wp_head', 'rsd_link'); //移除离线编辑器开放接口
    remove_action('wp_head', 'wlwmanifest_link'); //移除离线编辑器开放接口
    remove_action('wp_head', 'index_rel_link'); //去除本页唯一链接信息
    remove_action('wp_head', 'feed_links', 2); //移除feed
    remove_action('wp_head', 'feed_links_extra', 3); //移除feed
    remove_action('wp_head', 'rest_output_link_wp_head', 10); //移除wp-json链
    remove_action('wp_head', 'print_emoji_detection_script', 7); //头部的JS代码
    remove_action('wp_head', 'wp_print_styles', 8); //emoji载入css
    remove_action('wp_head', 'rel_canonical'); //rel=canonical
    add_filter('wp_resource_hints', 'remove_dns_prefetch', 10, 2); //头部加载DNS预获取（dns-prefetch）
}
add_action('init', 'jiangqie_remove_laji');


function jiangqie_setup()
{
    //关键字
    add_action('wp_head', 'jiangqie_seo_keywords');

    //页面描述 
    add_action('wp_head', 'jiangqie_seo_description');

    //网站图标
    add_action('wp_head', 'jiangqie_favicon');
}
add_action('after_setup_theme', 'jiangqie_setup');

/**
 * 缩略图
 */
function jiangqie_thumbnail_src()
{
    global $post;
    return jiangqie_thumbnail_src_d($post->ID, $post->post_content);
}

function jiangqie_thumbnail_src_d($post_id, $post_content)
{
    $post_thumbnail_src = '';
    if (has_post_thumbnail($post_id)) {    //如果有特色缩略图，则输出缩略图地址
        $thumbnail_src = wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'full');
        if(is_open_cos()){
            return replace_cos_url($thumbnail_src[0]);
        }
        $post_thumbnail_src = $thumbnail_src[0];
    } else {
        ob_start();
        ob_end_clean();
        $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post_content, $matches);
        if ($matches && isset($matches[1]) && isset($matches[1][0])) {
            $post_thumbnail_src = $matches[1][0];   //获取该图片 src
        }
    };
    return $post_thumbnail_src;
}


/**
 * 美化时间
 */
function jiangqie_time_ago($ptime)
{
    $ptime = strtotime($ptime);
    $etime = time() - $ptime;
    if ($etime < 1) return '刚刚';
    $interval = array(
        12 * 30 * 24 * 60 * 60  =>  '年前',// (' . date('Y-m-d', $ptime) . ')',
        30 * 24 * 60 * 60       =>  '个月前',// (' . date('m-d', $ptime) . ')',
        7 * 24 * 60 * 60        =>  '周前',// (' . date('m-d', $ptime) . ')',
        24 * 60 * 60            =>  '天前',
        60 * 60                 =>  '小时前',
        60                      =>  '分钟前',
        1                       =>  '秒前'
    );
    foreach ($interval as $secs => $str) {
        $d = $etime / $secs;
        if ($d >= 1) {
            $r = round($d);
            return $r . $str;
        }
    };
}

/**
 * 设置项的值
 */
$jiangqie_options = null;
function jiangqie_option($key)
{
    global $jiangqie_options;
    if (!$jiangqie_options) {
        $jiangqie_options = get_option('jiangqie_free');
    }
    return $jiangqie_options[$key];
}

/**
 * 设置文章浏览量
 */
function jiangqie_update_post_view_count()
{
    global $post;
    $post_views = (int) get_post_meta($post->ID, "views", true);
    if (!update_post_meta($post->ID, 'views', ($post_views + 1))) {
        add_post_meta($post->ID, 'views', 1, true);
    }
}


/**
 * 列表-浏览数
 */
function jiangqie_post_list_view_count()
{
    global $post;
    if (jiangqie_option('list_switch_view_count')) {
        $count = get_post_meta($post->ID, "views", true);
        if (!$count) {
            $count = 0;
        }
        echo '<cite>浏览 ' . $count . '</cite> ·';
    }

    echo '';
}

/**
 * 详情-浏览数
 */
function jiangqie_post_detail_view_count()
{
    global $post;
    if (jiangqie_option('detail_switch_view_count')) {
        $count = get_post_meta($post->ID, "views", true);
        if (!$count) {
            $count = 0;
        }
        echo '<cite>浏览 ' . $count . '</cite> ·';
    }

    echo '';
}

/**
 * 列表-点赞数
 */
function jiangqie_post_list_thumbup_count()
{
    global $post;
    if (jiangqie_option('list_switch_thumbup_count')) {
        $count = get_post_meta($post->ID, "jaingqie_thumbup", true);
        if (!$count) {
            $count = 0;
        }
        echo '<cite>点赞 ' . $count . '</cite> ·';
    }

    echo '';
}

/**
 * 详情-点赞数
 */
function jiangqie_post_detail_thumbup_count()
{
    global $post;
    if (jiangqie_option('detail_switch_thumbup_count')) {
        $count = get_post_meta($post->ID, "jaingqie_thumbup", true);
        if (!$count) {
            $count = 0;
        }
        echo '<cite>点赞 ' . $count . '</cite> ·';
    }

    echo '';
}

/**
 * 列表-评论数
 */
function jiangqie_post_list_comment_count()
{
    if (jiangqie_option('list_switch_comment_count')) {
        echo '<cite>评论 ' . get_comments_number() . '</cite> ·';
    }

    echo '';
}

/**
 * 详情-评论数
 */
function jiangqie_post_detail_comment_count()
{
    if (jiangqie_option('detail_switch_comment_count')) {
        echo '<cite>评论 ' . get_comments_number() . '</cite> ·';
    }

    echo '';
}

/**
 * 面包屑导航
 */
function jiangqie_breadcrumbs()
{
    if ((is_category() || is_tag()) && !jiangqie_option('list_switch_bread')) {
        return '';
    }

    if (is_single() && !jiangqie_option('detail_switch_bread')) {
        return '';
    }

    $delimiter = '<em> > </em>'; // 分隔符
    $before = '<span class="current">'; // 在当前链接前插入
    $after = '</span>'; // 在当前链接后插入
    if (!is_home() && !is_front_page() || is_paged()) {
        echo '<div class="base-list-nav" itemscope="">' . __('', 'cmp');
        global $post;
        $homeLink = home_url() . '/';
        echo '<a itemprop="breadcrumb" href="' . $homeLink . '">' . __('首页', 'cmp') . '</a> ' . $delimiter . ' ';
        if (is_404()) { // 404 页面
            echo $before;
            _e('Not Found', 'cmp');
            echo $after;
        } else if (is_category()) { // 分类 存档
            global $wp_query;
            $cat_obj = $wp_query->get_queried_object();
            $thisCat = $cat_obj->term_id;
            $thisCat = get_category($thisCat);
            $parentCat = get_category($thisCat->parent);
            if ($thisCat->parent != 0) {
                $cat_code = get_category_parents($parentCat, TRUE, ' ' . $delimiter . ' ');
                echo $cat_code = str_replace('<a', '<a itemprop="breadcrumb"', $cat_code);
            }
            echo $before . '' . single_cat_title('', FALSE) . '' . $after;
        } elseif (is_day()) { // 天 存档
            echo '<a itemprop="breadcrumb" href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
            echo '<a itemprop="breadcrumb"  href="' . get_month_link(get_the_time('Y'), get_the_time('m')) . '">' . get_the_time('F') . '</a> ' . $delimiter . ' ';
            echo $before . get_the_time('d') . $after;
        } elseif (is_month()) { // 月 存档
            echo '<a itemprop="breadcrumb" href="' . get_year_link(get_the_time('Y')) . '">' . get_the_time('Y') . '</a> ' . $delimiter . ' ';
            echo $before . get_the_time('F') . $after;
        } elseif (is_year()) { // 年 存档
            echo $before . get_the_time('Y') . $after;
        } elseif (is_single() && !is_attachment()) { // 文章
            if (get_post_type() != 'post') { // 自定义文章类型
                $post_type = get_post_type_object(get_post_type());
                $slug = $post_type->rewrite;
                echo '<a itemprop="breadcrumb" href="' . $homeLink . '/' . $slug['slug'] . '/">' . $post_type->labels->singular_name . '</a> ' . $delimiter . ' ';
                echo $before . get_the_title() . $after;
            } else { // 文章 post
                $cat = get_the_category();
                $cat = $cat[0];
                $cat_code = get_category_parents($cat, TRUE, ' ' . $delimiter . ' ');
                echo $cat_code = str_replace('<a', '<a itemprop="breadcrumb"', $cat_code);
                echo $before . '正文' . $after;
            }
        } elseif (!is_single() && !is_page() && get_post_type() != 'post') {
            $post_type = get_post_type_object(get_post_type());
            echo $before . $post_type->labels->singular_name . $after;
        } elseif (is_attachment()) { // 附件
            $parent = get_post($post->post_parent);
            $cat = get_the_category($parent->ID);
            $cat = $cat[0];
            echo '<a itemprop="breadcrumb" href="' . get_permalink($parent) . '">' . $parent->post_title . '</a> ' . $delimiter . ' ';
            echo $before . get_the_title() . $after;
        } elseif (is_page() && !$post->post_parent) { // 页面
            echo $before . get_the_title() . $after;
        } elseif (is_page() && $post->post_parent) { // 父级页面
            $parent_id = $post->post_parent;
            $breadcrumbs = [];
            while ($parent_id) {
                $page = get_page($parent_id);
                $breadcrumbs[] = '<a itemprop="breadcrumb" href="' . get_permalink($page->ID) . '">' . get_the_title($page->ID) . '</a>';
                $parent_id = $page->post_parent;
            }
            $breadcrumbs = array_reverse($breadcrumbs);
            foreach ($breadcrumbs as $crumb) echo $crumb . ' ' . $delimiter . ' ';
            echo $before . get_the_title() . $after;
        } elseif (is_search()) { // 搜索结果
            printf(__('搜索结果： <b style="color:#4680ff">%s</b>', 'cmp'), get_search_query());
        } elseif (is_tag()) { //标签 存档
            echo $before;
            printf(__('<b>标签:</b> %s', 'cmp'), single_tag_title('', FALSE));
            echo $after;
        } elseif (is_author()) { // 作者存档
            global $author;
            $userdata = get_userdata($author);
            echo $before;
            printf(__('作者: %s', 'cmp'), $userdata->display_name);
            echo $after;
        }

        if (get_query_var('paged')) { // 分页
            if (is_category() || is_day() || is_month() || is_year()  || is_tag() || is_author())
                echo sprintf(__('( Page %s )', 'cmp'), get_query_var('paged'));
        }
        echo '</div>';
    }
}

/**
 * 首页精选文章
 */
function home_post_recommend()
{
    $hot_ids = jiangqie_option('home_post_recommend');
    if (empty($hot_ids)) {
        return false;
    }

    $args = [
        'post__in' => $hot_ids,
        'orderby' => 'post__in',
        'posts_per_page' => -1,
        'ignore_sticky_posts' => 1
    ];

    $hots = [];
    $query = new WP_Query();
    $result = $query->query($args);
	foreach ($result as $post) {
		$thumbnail = jiangqie_thumbnail_src_d($post->ID, $post->post_content);
		if (empty($thumbnail)) {
			$thumbnail = get_stylesheet_directory_uri() . '/images/jiangqie.png';
		}
		$hots[] = [
			'id' => $post->ID,
			'title' => $post->post_title,
			'thumbnail' => $thumbnail
		];
	}

    if (empty($hots)) {
        return false;
    }

    return $hots;
}

/**
 * 底部热门推荐文章
 */
function footer_hot_recommend()
{
    $hot_ids = jiangqie_option('footer_hot_recommend');
    if (empty($hot_ids)) {
        return false;
    }

    $args = [
        'post__in' => $hot_ids,
		'orderby' => 'post__in',
        'posts_per_page' => -1,
        'ignore_sticky_posts' => 1
    ];

    $hots = [];
    $query = new WP_Query();
    $result = $query->query($args);
	foreach ($result as $post) {
		$hots[] = [
			'id' => $post->ID,
			'title' => $post->post_title
		];
	}

    if (empty($hots)) {
        return false;
    }

    return $hots;
}

/* ---- SEO start ---- */
//标题
function jiangqie_seo_title()
{
    $site_title = jiangqie_option('site_title');
    if (is_home() && !empty($site_title)) {
        echo $site_title;
    } else {
        global $page, $paged;
        wp_title('-', true, 'right');

        // 添加网站标题.
        bloginfo('name');

        // 如果有必要，在标题上显示一个页面数.
        if ($paged >= 2 || $page >= 2) {
            echo ' - ' . sprintf('第%s页', max($paged, $page));
        }
    }
}

//关键字
function jiangqie_seo_keywords()
{
    global $s, $post;
    $keywords = '';
    if (is_single()) {
        if (get_the_tags($post->ID)) {
            foreach (get_the_tags($post->ID) as $tag) $keywords .= $tag->name . ', ';
        }
        foreach (get_the_category($post->ID) as $category) $keywords .= $category->cat_name . ', ';
        $keywords = substr_replace($keywords, '', -2);
    } elseif (is_home()) {
        $keywords = jiangqie_option('site_keyword');
    } elseif (is_tag()) {
        $keywords = single_tag_title('', false);
    } elseif (is_category()) {
        $keywords = single_cat_title('', false);
    } elseif (is_search()) {
        $keywords = esc_html($s, 1);
    } else {
        $keywords = trim(wp_title('', false));
    }
    if ($keywords) {
        echo "<meta name=\"keywords\" content=\"$keywords\">\n";
    }
}

//描述
function jiangqie_seo_description()
{
    global $s, $post;
    $description = '';
    $blog_name = get_bloginfo('name');
    if (is_singular()) {
        if (!empty($post->post_excerpt)) {
            $text = $post->post_excerpt;
        } else {
            $text = $post->post_content;
        }
        $description = trim(str_replace(array("\r\n", "\r", "\n", "　", " "), " ", str_replace("\"", "'", strip_tags($text))));
        if (!($description)) $description = $blog_name . "-" . trim(wp_title('', false));
    } elseif (is_home()) {
        $description = jiangqie_option('site_description');
    } elseif (is_tag()) {
        $description = $blog_name . "'" . single_tag_title('', false) . "'";
    } elseif (is_category()) {
        $description = trim(strip_tags(category_description()));
    } elseif (is_archive()) {
        $description = $blog_name . "'" . trim(wp_title('', false)) . "'";
    } elseif (is_search()) {
        $description = $blog_name . ": '" . esc_html($s, 1) . "' 的搜索結果";
    } else {
        $description = $blog_name . "'" . trim(wp_title('', false)) . "'";
    }
    $description = mb_substr($description, 0, 220, 'utf-8');
    echo "<meta name=\"description\" content=\"$description\">\n";
}
/* ---- SEO end ---- */

/**
 * 站点LOGO
 */
function jiangqie_site_logo()
{
    $logo = jiangqie_option('site_logo');
    if ($logo && $logo['url']) {
        echo '<img src="' . $logo['url'] . '" alt="' . get_bloginfo('name') . '" />';
    } else {
        echo "";
    }
}

/**
 * favicon
 */
function jiangqie_favicon()
{
    $favicon = jiangqie_option('site_favicon');
    if ($favicon && $favicon['url']) {
        echo '<link rel="shortcut icon" type="image/x-icon" href="' . $favicon['url'] . '" />';
    } else {
        echo '';
    }
}

/**
 * 首页显示分类
 */
function jiangqie_nav_catsegories()
{
    $home_cat_hide = jiangqie_option('home_cat_hide');
    if (!empty($home_cat_hide)) {
        $home_cat_hide = implode(",", $home_cat_hide);
        $args = ['exclude' => $home_cat_hide];
    } else {
        $args = [];
    }

//    $categories = array_reverse(get_categories($args));
    $categories = get_categories($args);
    return $categories;
}

//评论样式
function jiangqie_comment_list($comment, $args, $depth)
{
    echo '<div class="content-comment-item content-comment-item-depth-' . $depth . '">';
    echo '<p class="simple-info">';
    echo '<a href="' . ($comment->comment_author_url ? $comment->comment_author_url : '#') . '" title="">';

    jiangqie_avatar($comment->user_id);

    $comment_author = get_user_meta($comment->user_id, 'nickname', true);
    if (empty($comment_author)) {
        $comment_author = $comment->comment_author;
    }

    echo '<em>' . $comment_author  . '</em>';

    echo '</a>';
    echo comment_reply_link(array_merge($args, array('add_below' => 'div-comment', 'depth' => $depth, 'max_depth' => $args['max_depth'])));
    echo edit_comment_link();
    echo get_comment_time('Y-m-d H:i ');
    echo '</p>';
    echo '<div class="content-comment-info">';
    echo '<p class="content-comment-text">' . get_comment_text() . '</p>';
    echo '</div>';
    echo '</div>';
}

/**
 * 打赏图片
 */
function jiangqie_reward_image()
{
    $image = jiangqie_option('detail_reward_image');
    if ($image && $image['url']) {
        echo '<img src="' . $image['url'] . '" alt="' . get_bloginfo('name') . '" />';
    } else {
        echo '请在后台配置打赏二维码';
    }
}

/**
 * 酱茄头像
 */
function jiangqie_avatar($user_id)
{
    $avatar = get_user_meta($user_id, 'jiangqie_avatar', true);
    if (empty($avatar)) {
        $avatar = get_stylesheet_directory_uri() . '/images/default_avatar.jpg';
    }

    echo '<img alt="" src="' . $avatar . '" />';
}


// 禁用多种格式的图片
function disable_intermediate_image_sizes($size){
    $size = [];
    return $size;
}
add_filter("intermediate_image_sizes","disable_intermediate_image_sizes");

// 禁止图片缩放
add_filter("big_image_size_threshold","__return_false");

// 禁止生成thumbnail
// 禁用其他图片尺寸
function disable_other_image_sizes() {
    remove_image_size('post-thumbnail'); // disable images added via set_post_thumbnail_size()
}
add_action('init', 'disable_other_image_sizes');

//下载图片
/**
 * @param $img 远程图片路径
 * @param $path 本地图片地址
 * @return bool|int
 */
function download_image($img,$path){

    //python
    $cmd = "python3 download_image.py $img " . ABSPATH . $path;
    exec($cmd,$out,$status);
    return $out;









//    ////////////////////
    //   以下废弃，废弃，废弃
    /////////////////

//    $arrContextOptions=array(
//        "ssl"=>array(
//            "verify_peer"=>false,
//            "verify_peer_name"=>false,
//        ),
//    );
//    $image = file_get_contents($img,false,stream_context_create($arrContextOptions));
//
//    $save_path = ABSPATH . $path;
//
//    return file_put_contents($save_path, $image); //Where to save the image


    $ch  = curl_init($img);
    curl_setopt($ch, CURLOPT_POST, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
//    curl_setopt($ch, CURLOPT_PROXY, "127.0.0.1:1087");//暂时不使用
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36']);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3600);
    curl_setopt($ch, CURLOPT_BUFFERSIZE, 20971520);
    curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V6);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    $output = curl_exec($ch);
    curl_close($ch);

    $save_path = ABSPATH . $path;

    return file_put_contents($save_path, $output); //Where to save the image

}

function downloadBase64image($base64,$fileinfo){

    //判断是否有逗号 如果有就截取后半部分
    if (strstr($base64,",")){
        $image = explode(',',$base64);
        $image = $image[1];
    }
    //设置图片保存路径
    $path = ABSPATH . $fileinfo['path'];

    //判断目录是否存在 不存在就创建
    if (!is_dir($path)){
        mkdir($path,0777,true);
    }

    //图片路径
    $imageSrc= ABSPATH . $fileinfo['path_name'];

    //生成文件夹和图片
    $r = file_put_contents($imageSrc, base64_decode($image));


    if (!$r) {
        return false;
    }else {
        return true;
    }
}

//disable update
//add_filter('pre_site_transient_update_core',function(){return null;}); // 关闭核心提示
//add_filter('pre_site_transient_update_plugins',function(return null;}); // 关闭插件提示
//add_filter('pre_site_transient_update_themes',function(){return null;}); // 关闭主题提示
//remove_action('admin_init', '_maybe_update_core'); // 禁止 WordPress 检查更新
//remove_action('admin_init', '_maybe_update_plugins'); // 禁止 WordPress 更新插件
//remove_action('admin_init', '_maybe_update_themes'); // 禁止 WordPress 更新主题
add_filter( 'automatic_updater_disabled', '__return_true' );

//性能优化
//彻底关闭 pingback
add_filter('xmlrpc_methods',function($methods){
    $methods['pingback.ping'] = '__return_false';
    $methods['pingback.extensions.getPingbacks'] = '__return_false';
    return $methods;
});
//禁用 pingbacks, enclosures, trackbacks
remove_action( 'do_pings', 'do_all_pings', 10 );
//去掉 _encloseme 和 do_ping 操作。
remove_action( 'publish_post','_publish_post_hook',5 );

//禁用emoji
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('embed_head', 'print_emoji_detection_script');

remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');

//屏蔽字符转码
add_filter('run_wptexturize', '__return_false');
//屏蔽gutenbery编辑器
add_filter('use_block_editor_for_post_type', '__return_false');
//去除掉block插件
add_filter("should_load_block_editor_scripts_and_styles",function (){return false;});

//登陆保护
function login_protection(){
    if($_GET['word'] != 'fpvone')header('Location: /404');
}
add_action('login_enqueue_scripts','login_protection');

//获取cos客户端
function COS_Client(){
    require_once 'inc/cos-php-sdk-v5/vendor/autoload.php';

    $secretId = "AKIDK0PcfDUz8Ks2eZwHVOrjIWRrBmkjxHxt"; //"云 API 密钥 SecretId";
    $secretKey = "xeD8HI3C4G8EXoqqGsQNpr7tJEI0KlDb"; //"云 API 密钥 SecretKey";
    $region = "ap-shanghai"; //设置一个默认的存储桶地域
    $cosClient = new Qcloud\Cos\Client(
        array(
            'region' => $region,
            'schema' => 'https', //协议头部，默认为http
            'credentials'=> array(
                'secretId'  => $secretId ,
                'secretKey' => $secretKey)));
    return $cosClient;
}

//添加图片到cos
function upload_img_to_cos($local_abs_path,$cos_path){

    $cosClient = COS_Client();

    ### 上传文件流
    try {
        $bucket = "17fpv-1251568218"; //存储桶名称 格式：BucketName-APPID
        $key = $cos_path;
        $srcPath = $local_abs_path;//本地文件绝对路径
        $file = fopen($srcPath, 'rb');
        if ($file) {
            $result = $cosClient->Upload(
                $bucket = $bucket,
                $key = $key,
                $body = $file);
        }
    } catch (\Exception $e) {
        echo "$e\n";
    }


    //上传文件到onedrive
//    $cmd = "/usr/local/php/bin/php /home/wwwroot/storage.17fpv.com/Oneindex-master/one.php upload:file {$local_abs_path} /Drone/share{$cos_path}";
    $cmd = "/usr/local/php/bin/php /home/wwwroot/olaindex/artisan upload {$local_abs_path} /Drone/share{$cos_path}";
    exec($cmd,$out,$status);

    //上传之后就删除本地文件


}

//删除cos图片
function delete_img_from_cos($cos_path) {

    $cosClient = COS_Client();

    try {
        $bucket = "17fpv-1251568218"; //存储桶名称 格式：BucketName-APPID
        $key = $cos_path; //对象在存储桶中的位置，即称对象键
        $result = $cosClient->deleteObject(array(
            'Bucket' => $bucket,
            'Key' => $key,
            'VersionId' => 'string'
        ));
        return $result;
    } catch (\Exception $e) {
        // 请求失败
        echo($e);
    }
}

//支持webp上传
function mimvp_filter_mime_types( $array ) {
    $array['webp'] = 'image/webp';
    return $array; 
}
add_filter( 'mime_types', 'mimvp_filter_mime_types', 10, 1 );

//上传图片后添加到oss源头
add_filter( 'wp_handle_upload', 'handle_upload_img', 10, 2 );
function handle_upload_img( $upload, $context ) {
  //* Do something interesting
    if(isImage($upload['file'])){
        // if($upload['type']!='image/webp'){
        //     $file_arr = explode('.',$upload['file']);
        //     $file_arr[len($file_arr)-1] = 'webp';
        //     $webp_file = implode('.', $file_arr);

        //     $url_arr = explode('.',$upload['url']);
        //     $url_arr[len($url_arr)-1] = 'webp';
        //     $webp_url = implode('.', $url_arr);
        //     //转化成webp图片
        //     imagewebp($upload['file'],$webp_file,75);
        //     //上传到cos
        //     upload_img_to_cos($webp_file, parse_url($webp_url)['path']);
        //     //删除原本的jpg文件
        //     unlink($upload['file']);
        // }else{
            upload_img_to_cos($upload['file'], parse_url($upload['url'])['path']);
        // }
    }
    return $upload;
}

//添加编辑器样式
function my_theme_add_editor_styles() {
    add_editor_style( "css/markdown.css" );
}
add_action( "init", "my_theme_add_editor_styles" );

//删除附件后删除缓存

function isImage($filename) {
    $types = '.gif|.jpeg|.png|.bmp|.webp';  //定义检查的图片类型
    if(file_exists($filename))
    {
        $info = @getimagesize($filename);
        $ext = image_type_to_extension($info['2']);
        return stripos($types,$ext);
    }else {
        return false;
    }
}

// define the wp_delete_file callback
function filter_wp_delete_file( $file ) {
    if(isImage($file)){
        delete_img_from_cos(str_replace(ABSPATH,'/',$file));
    }
    // make filter magic happen here...
    return $file;
};

// add the filter
add_filter( 'wp_delete_file', 'filter_wp_delete_file', 10, 1 );

//自定义分页样式
function custom_pagination($catid, $tagid, $current_page){
    $args = [];
    if($catid){
        $args = [
            'taxonomy' => 'category',
            'field' => 'id',
            'terms' => $catid
        ];
    }
    if($tagid){
        $args = [
            'taxonomy' => 'post_tag',
            'field' => 'id',
            'terms' => $tagid
        ];
    }
    $q = new WP_Query( array(
        'nopaging' => true,
        'tax_query' => array(
            array(
                'field' => 'id',
                'include_children' => false,
            )+$args,
        ),
        'fields' => 'ids',
    ) );
    $post_count = $q->post_count;
    $limit = 10;//每页数量

    $total_page = ceil($post_count/$limit);

    echo '<div class="pagination">';
    echo '    <ul>';

    if($total_page <= 5){
        for ($i=1;$i<=$total_page;$i++) {
            if ($i==$current_page) {
                $active = "class='active'";
            }else{
                $active = '';
            }
            echo '    <li '.$active.'><a href="?page='.$i.'">'.$i.'</a></li>';
        }
    }else{
        if($current_page > 3){
            echo '    <li><a href="?page=1">首页</a></li>';
        }
        $prev_buchong = 2-$total_page+$current_page;
        for ($i=2+$prev_buchong;$i>2;$i--){
            $prev_now = $current_page-$i;
            echo '    <li><a href="?page='.$prev_now.'">'.$prev_now.'</a></li>';
        }
        if(($current_page-2) > 0){
            $prev_2 = $current_page-2;
            echo '    <li><a href="?page='.$prev_2.'">'.$prev_2.'</a></li>';
        }
        if(($current_page-1) > 0){
            $prev_1 = $current_page-1;
            echo '    <li><a href="?page='.$prev_1.'">'.$prev_1.'</a></li>';
        }
        echo '    <li class="active"><a href="?page='.$current_page.'">'.$current_page.'</a></li>';
        if (($current_page+1) <= $total_page){
            $next_1 = $current_page+1;
            echo '    <li><a href="?page='.$next_1.'">'.$next_1.'</a></li>';
        }
        if (($current_page+2) <= $total_page){
            $next_2 = $current_page+2;
            echo '    <li><a href="?page='.$next_2.'">'.$next_2.'</a></li>';
        }
        if($current_page==1 || $current_page==2){
            if (isset($next_2) && ($next_2+1)<=$total_page){
                $next_3 = $next_2 + 1;
                echo '    <li><a href="?page='.$next_3.'">'.$next_3.'</a></li>';
            }
        }
        if($current_page==1){
            if (isset($next_2) && ($next_2+2)<=$total_page){
                $next_4 = $next_2 + 2;
                echo '    <li><a href="?page='.$next_4.'">'.$next_4.'</a></li>';
            }
        }
        if($current_page < ($total_page-2)){
            echo '    <li><a href="?page='.$total_page.'">末页</a></li>';
        }
    }
    echo '    </ul>';
    echo '</div>';
}

//评论时发送私信
function when_change_comment_status( $comment_ID, $comment_status ) {
    //评论如果通过，就向父评论推送消息
    if( $comment_status == 'approve' ){
        //function logic goes here
        //获取父评论ID
        global $wpdb;
        $comment = $wpdb->get_row("select * from wp_comments where comment_ID={$comment_ID}");
        $comment_parent = $comment->comment_parent;
        if($comment_parent > 0){//如果有父评论，进入评论体系
            $comment_meta = get_comment_meta($comment_ID);
            //如果是超级管理员，生成meta信息
            if($comment->user_id==1 && !$comment_meta){
                add_comment_meta($comment_ID,'is_send_msg',0,true);
                $comment_meta = get_comment_meta($comment_ID);
            }
            if($comment_meta){
                if($comment_meta['is_send_msg'][0] == 0){//如果没有发送消息，触发消息
                    //获取回复者信息
                    $userdata = get_userdata($comment->user_id);

                    //被回复者信息
                    $comment_parent_info = $wpdb->get_row("select * from wp_comments where comment_ID={$comment_parent}");
                    $parent_userdata = get_userdata($comment_parent_info->user_id);
                    if ($parent_userdata){
                        //如果被回复者邮箱不是17fpv.com结果的，则认为来源是网站的，不是从微信登陆的，不给予推送
                        if(strpos($parent_userdata->data->user_email,'17fpv.com')===false){
                            return ;
                        }

                        //获取access_token
                        $token = get_access_token();
                        $openid = $parent_userdata->data->user_login;
                        $template_id = "s6OhOmbSel_TRYxkUi8h0qcKh3gKJMU9u6Un77c7L0A";
                        $page  = "/pages/article/article?post_id=".$comment->comment_post_ID;
                        $data = [
                            'thing1'=>['value'=>$userdata->data->display_name],
                            'thing2'=>['value'=>$comment->comment_content],
                            'time3'=>['value'=>$comment->comment_date_gmt]
                        ];
                        $params = [
                            'access_token' => $token,
                            'touser' => $openid,
                            'template_id' => $template_id,
                            'page' => $page,
                            'data' => $data
                        ];
                        $args = array(
                            'method'  => 'POST',
                            'body' 	  => wp_json_encode($params),
                            'headers' => array(),
                            'cookies' => array()
                        );
                        $api = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$token;
                        $res = wp_remote_post($api, $args);
                        //标记为1，不重复发送
                        update_comment_meta($comment_ID,'is_send_msg',1,0);
                    }
                }
            }
        }
    }
}
function get_access_token(){
    $token = '';
    $path_token = JIANG_QIE_API_BASE_DIR . 'wx_access_token.data';
    if (file_exists($path_token)) {
        $str_token = file_get_contents($path_token);
        $access_token = json_decode($str_token, TRUE);
        if ($access_token['expires_in'] > time()) {
            $token =  $access_token['access_token'];
        }
    }
    if(!$token){
        wp_remote_get(site_url()."/wp-json/jiangqie/v1/posts/refresh_token");
        $str_token = file_get_contents($path_token);
        $access_token = json_decode($str_token, TRUE);
        if ($access_token['expires_in'] > time()) {
            $token =  $access_token['access_token'];
        }
    }
    return $token;
}
add_action( 'wp_set_comment_status', 'when_change_comment_status', 10, 3 );
//禁止过滤html标签
remove_action('init', 'kses_init');
remove_action('set_current_user', 'kses_init');

function generate_xml(){
    $content = "<?xml version='1.0' encoding='UTF-8'?>";
    $content .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">';
    $content .= '<url>';
    $content .= '<loc>'.get_home_url().'</loc>';
    $content .= '<lastmod>'.date("Y-m-d",time()).'</lastmod>';
    $content .= '<changefreq>daily</changefreq>';
    $content .= '<priority>1.0</priority>';
    $content .= '</url>';

    $urls = [];

    /* 文章页面 */ 
    $myposts = get_posts( "numberposts=5000" );
    foreach( $myposts as $post ) {
        $content .= '<url>';
        $content .= '<loc>'.get_home_url().'/'.$post->ID.'.html</loc>';
        $content .= '<lastmod>'.date("Y-m-d", strtotime($post->post_date)).'</lastmod>';
        $content .= '<changefreq>monthly</changefreq>';
        $content .= '<priority>0.8</priority>';
        $content .= '</url>';

        // $urls[] = get_home_url().'/'.$post->ID.'.html';
    }

    /* 博客分类 */ 
    $terms = get_terms('category', 'orderby=name&hide_empty=0' );
    $count = count($terms);
    if($count > 0){
        foreach ($terms as $term) {
            $content .= '<url>';
            $content .= '<loc>'.get_term_link($term, $term->slug).'</loc>';
            $content .= '<changefreq>weekly</changefreq>';
            $content .= '<priority>0.8</priority>';
            $content .= '</url>';

            // $urls[] = get_term_link($term, $term->slug);
        }
    }

    /* 配件详情页 */
    global $wpdb;
    $parts = $wpdb->get_results("select id from parts");
    foreach ($parts as $part) {
        $content .= '<url>';
        $content .= '<loc>'.get_home_url()."/category/parts/info/".$part->id.'.html</loc>';
        $content .= '<changefreq>weekly</changefreq>';
        $content .= '<priority>0.6</priority>';
        $content .= '</url>';

        $urls[] = get_home_url()."/category/parts/info/".$part->id.'.html';
    }

    /* 标签(可选) */
    $tags = get_terms("post_tag");
    foreach ( $tags as $key => $tag ) {
	    $link = get_term_link( intval($tag->term_id), "post_tag" );
	    if ( is_wp_error( $link ) )
		    return false;
		$tags[ $key ]->link = $link;

        $content .= '<url>';
        $content .= '<loc>'.$link.'</loc>';
        $content .= '<changefreq>monthly</changefreq>';
        $content .= '<priority>0.4</priority>';
        $content .= '</url>';

        // $urls[] = $link;
    }

    $content .= '</urlset>';
    return ['content' => $content, 'urls' => $urls];
}

add_action('delete_post', 'custom_delete_post');
function custom_delete_post($post_id){

}


/* 删除文章时删除图片附件
/* ------------------------ */
function delete_post_and_attachments($post_ID) {
    global $wpdb;
//删除特色图片
    $thumbnails = $wpdb->get_results( "SELECT * FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );
    foreach ( $thumbnails as $thumbnail ) {
        wp_delete_attachment( $thumbnail->meta_value, true );
    }
//删除图片附件
    $attachments = $wpdb->get_results( "SELECT * FROM $wpdb->posts WHERE post_parent = $post_ID AND post_type = 'attachment'" );
    foreach ( $attachments as $attachment ) {
        wp_delete_attachment( $attachment->ID, true );
    }
    $wpdb->query( "DELETE FROM $wpdb->postmeta WHERE meta_key = '_thumbnail_id' AND post_id = $post_ID" );
    //删除 spider_fpv
    $spider_fpv = $wpdb->get_row( "SELECT *  from spider_fpv where wp_posts_id = {$post_ID}");

    if($spider_fpv){
        $photos = $spider_fpv->photos ? explode(',',$spider_fpv->photos) : null;

        if($photos){
            foreach ($photos as $photo){
                //删除本地图片
                unlink(ABSPATH . $photo);
                unlink(ABSPATH . $photo.tinyjpg());
                //删除cos图片
                delete_img_from_cos($photo);
                delete_img_from_cos($photo.tinyjpg());
            }
        }
    }

    //删除FPV——parts关系
    $wpdb->query( "DELETE FROM fpv_parts WHERE fpv_id = {$post_ID}" );

    //删除user_post关系
    $wpdb->query( "DELETE FROM user_post WHERE wp_posts_id = {$post_ID}" );

}
add_action('before_delete_post', 'delete_post_and_attachments');


add_action('save_post', 'custom_update_post');
function custom_update_post($post_id){
    if($post_id == 266){
        $data = generate_xml();
    
        file_put_contents(ABSPATH."/sitemap.xml", $data['content'], FILE_TEXT );
        file_put_contents(ABSPATH."/urls.txt", implode("\r\n", $data['urls']), FILE_TEXT );

        update_xml_to_baidu($data['urls']);
    }
}

function update_xml_to_baidu($urls){
    $urls = $urls;
    $api = 'http://data.zz.baidu.com/urls?site=https://www.17fpv.com&token=ZsyABzec9tR70sFu';
    $ch = curl_init();
    $options =  array(
        CURLOPT_URL => $api,
        CURLOPT_POST => true,
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_POSTFIELDS => implode("\n", $urls),
        CURLOPT_HTTPHEADER => array('Content-Type: text/plain'),
    );
    curl_setopt_array($ch, $options);
    $result = curl_exec($ch);
    echo $result;
}

//控制小程序视频展示
function is_show_video(){
    return true;
}
//cos配置

//获取静态资源链接
function get_cos_domain(){
//    return "https://17fpv-1251568218.cos.ap-shanghai.myqcloud.com";
    return "https://r2-worker.devtool.uk/Drone/share";
}
function is_open_cos(){
    return true;
}
//换成cos的域名
function replace_cos_url($url){
//    return "https://17fpv-1251568218.cos.ap-shanghai.myqcloud.com/WX20200724-023326%402x.png";
    return str_replace(site_url(),get_cos_domain(),"$url");
}

//.tiny.jpg_suffix 后缀（当时为了省带宽设置的，现在不用了）
function tinyjpg(){
//    return ".tiny.jpg";
    return null;
}

//替换附件标签为cdn的

add_filter('wp_get_attachment_url', 'honor_ssl_for_attachments');
function honor_ssl_for_attachments($url) {
    if(is_open_cos()){
        $url = str_replace(site_url(), get_cos_domain(), $url);
        return $url;
    }else{
        return $url;
    }
//    $http = site_url(FALSE,$http = site_url(FALSE, 'http');
////    $https = site_url(FALSE, 'https');
////    return ( $_SERVER['HTTPS'] == 'on' ) ? str_replace($http, $https, $url) : $url; 'http');
//    $https = site_url(FALSE, 'https');
//    return ( $_SERVER['HTTPS'] == 'on' ) ? str_replace($http, $https, $url) : $url;
}


